const db = require('../config/database');
const logger = require('../config/logger');

/**
 * 记录系统日志到数据库
 * @param {string} level - 日志级别: info, warning, error
 * @param {string} action - 操作类型: login, logout, upload, download, delete, etc.
 * @param {string} content - 日志内容描述
 * @param {object} options - 可选参数
 * @param {number} options.userId - 用户ID
 * @param {string} options.userType - 用户类型: admin, user, system
 * @param {string} options.ipAddress - IP地址
 */
async function logSystemAction(level, action, content, options = {}) {
  try {
    const {
      userId = null,
      userType = 'system',
      ipAddress = null
    } = options;

    await db.query(
      `INSERT INTO system_logs (level, action, content, user_id, user_type, ip_address, created_at)
       VALUES (?, ?, ?, ?, ?, ?, NOW())`,
      [level, action, content, userId, userType, ipAddress]
    );

    logger.info(`系统日志记录: [${level}] ${action} - ${content}`);
  } catch (error) {
    // 记录日志失败不应该影响主业务流程，只输出错误日志
    logger.error('记录系统日志失败:', error);
  }
}

/**
 * 便捷方法：记录信息级别日志
 */
function logInfo(action, content, options = {}) {
  return logSystemAction('info', action, content, options);
}

/**
 * 便捷方法：记录警告级别日志
 */
function logWarning(action, content, options = {}) {
  return logSystemAction('warning', action, content, options);
}

/**
 * 便捷方法：记录错误级别日志
 */
function logError(action, content, options = {}) {
  return logSystemAction('error', action, content, options);
}

module.exports = {
  logSystemAction,
  logInfo,
  logWarning,
  logError
};
